package cn.yusei.teamTribe.controller.team;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.yusei.teamTribe.constant.ResponseCode;
import cn.yusei.teamTribe.constant.TextType;
import cn.yusei.teamTribe.entity.Team;
import cn.yusei.teamTribe.exception.TeamIdNotFoundException;
import cn.yusei.teamTribe.service.TextFilterService;
import cn.yusei.teamTribe.service.team.TeamInfoService;
import cn.yusei.teamTribe.util.ResponseUtil;

@Controller
public class TeamInfoController {

	@Autowired
	private TeamInfoService teamInfoService;
	@Autowired
	private TextFilterService textFilterService;
	
	@RequestMapping(value = "/teamInfo/update")
	public void update(@RequestAttribute int id, Team team,PrintWriter out){
		team.setName(textFilterService.getFilterString(team.getName(), TextType.TEAM_INFO));
		if(team.getId() <= 0 || !team.isValid()){
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		int code;
		try {
			code = teamInfoService.update(id, team);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
			return;
		}
		ResponseUtil.responseCode(out, code);
		
	}
	
	@RequestMapping(value="/teamInfo/get")
	public void get(@RequestParam int id, PrintWriter out)
	{
		if(id <= 0)
		{
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		Team team = null;
		try
		{
			team = teamInfoService.getById(id);
		}
		catch (TeamIdNotFoundException e)
		{
			ResponseUtil.responseCode(out, ResponseCode.TEAM_NOT_EXISTS);
			return;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
			return;
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("team", team);
		ResponseUtil.response(out, ResponseCode.REQUEST_SUCCESSED, param);
	}
	
}
